<template>
  <div class="coupon_detail">
      <cube-scroll class="scroll" ref="scroll" :style="{height:page_height+'px'}">

          <!--S卡券信息-->
          <div id="coupon" :class="coupon.coupon_type ? coupon.coupon_type : 'hd'">
              <p class="type" v-if="coupon.type">{{coupon.type}}</p>
              <img class="icon" v-if="coupon.icon" :src="coupon.icon" />
              <p class="cost"  v-if="coupon.type">{{coupon.cost}}</p>
              <p class="name">{{coupon.name}}</p>
              <p class="number">数量:{{coupon.number}}&nbsp;&nbsp;已核销:{{coupon.use_number}}</p>
              <div class="time">{{coupon.time}}</div>
              <div class="status exchange" v-if="coupon.use_number >= coupon.number"><i class="iconfont icon-quanxiangqingyeiconyihexiao"></i></div>
              <div class="status" v-if="coupon.use_number < coupon.number && coupon.expires"><i class="iconfont icon-yiguoqi"></i></div>
          </div>
          <!--E卡券信息-->

          <!--S卡券奖品的相关图片-->
          <div id="images" v-if="images.length > 0">
              <h2>相关图片</h2>
              <img v-for="(item,index) in images" :src="item" v-bind:key="item" @click="showSlide(index)" />
          </div>
          <!--E卡券奖品的相关图片-->

          <!--S门店信息-->
          <div id="store" v-if="store.id != 0">
              <img class="logo" ref="storeLogo" :src="store.logo" />
              <p class="name" ref="storeName" :style="{top:store_name_top+'px'}">{{store.name}}</p>
              <p class="address">门店地址:{{store.address}}</p>
              <div id="store-position" v-if="store.position.length > 0" @touchstart.stop></div>
          </div>
          <!--E门店信息-->

          <!--S活动后台核销地址-->
          <div id="after-address" v-else>
              使用地址:{{after_address}}
          </div>
          <!--S活动后台核销地址-->

          <!--S卡券使用规则-->
          <div id="rule">
              <h2>使用规则</h2>
              <div class="content">{{coupon.rule}}</div>
          </div>
          <!--E卡券使用规则-->

      </cube-scroll>

      <!--S底部核销按钮-->
      <div id="footer" ref="footer">
          <cube-button :primary="true" @click="clickAfterBtn" :disabled="coupon.use_number >= coupon.number || coupon.expires">
              <svg class="qrcode-iconfont" aria-hidden="true">
                  <use xlink:href="#icon-erweima"></use>
              </svg>
              <span class="text">使用卡券</span>
          </cube-button>
      </div>
      <!--E底部核销按钮-->

      <!--S核销码-->
      <div id="after" v-show="after_show">
          <div class="close" @click="clickCloseAfter"><i class="cubeic-close"></i></div>
          <div class="after">
              <h2>店员扫一扫进行核销</h2>
              <img class="qrcode" :src="qrcode.src" />
              <div class="past" v-show="refresh_qrcode > 0" @click="clickRefreshQrcode">
                  <div class="past-content">
                      <img v-show="refresh_qrcode == 1" src="./images/refresh.png" />
                      <img v-show="refresh_qrcode == 2" src="./images/refresh.svg" />
                      已过期,点击刷新
                  </div>
              </div>
          </div>
      </div>
      <!--E核销码-->

  </div>
</template>

<script>
import store from "../../store.js";
export default {
    name: "coupon_detail",
    data(){
        return {
            page_height:document.documentElement.clientHeight,  //页面高度
            snapshot_id:0,  //对应的会员抢到的宝藏id
            store_id:0,  //门店id
            activity_id:0,  //活动id
            after_address:"",  //活动投放的卡券核销地址
            store_name_top:0,   //门店的名称top值 作为门店名称和门店logo垂直居中
            coupon:{  //卡券信息
                name:"",  //卡券名称
                cost:"",  //卡券面值信息
                type:"",  //卡券类型
                time:"",  //卡券有效期
                rule:"",  //卡券使用规则
                images:[], //卡券的相关图片
                expires:false,  //卡券是否过期
                number:0,   //卡券数量
                use_number:0  //使用数量
            },
            store:{  //门店信息
                id:0,
                name:"",
                logo:"",
                address:"",
                position:[]   //门店定位经纬度
            },
            //门店定位地图对象
            position_map:{
                map:null,   //地图对象
            },
            after_show:false,  //是否显示核销区域
            refresh_qrcode:0,  //是否刷新核销二维码中
            qrcode:{
                src:"",  //二维码地址
                expire:""  //过期时间
            }
        };
    },
    computed:{
        images(){
            var images = [];
            if(this.coupon.images){
                this.coupon.images.forEach((item)=>{
                    images.push(this.$sysinfo.attachurl+item);
                });
            }
            return images;
        }
    },
    created(){
        this.snapshot_id = this.$route.params.snapshot_id;
        this.findCoupon(this.snapshot_id)
            .then(()=>{
                if(this.store.position.length > 0){
                    this.storeMapPosition();
                }
            })
            .then(()=>{
                this.findActivityAfterAddress();
            })
            .catch(error=>{
                this.iError(error);
            });
    },
    mounted(){
            this.$nextTick(() => {
                setTimeout(() => {
                    if(this.store.id != 0) this.store_name_top = (this.$refs.storeLogo.getBoundingClientRect().height - this.$refs.storeName.getBoundingClientRect().height) / 2;
                }, 100);
            });
    },
    beforeDestroy(){
      clearInterval(store.state.coupon_after_expire_timer);
      clearInterval(store.state.coupon_timer);
    },
    methods:{
        //获取卡券信息
        findCoupon(){
            return new Promise((success,error)=>{
                this.$http.post(this.$sysinfo.url,this.$qs.stringify({
                    pages:"couponSnapshot",
                    doing:"findOne",
                    snapshot_id:this.snapshot_id
                }))
                    .then((res)=>{
                        if(res.data.status == "success"){
                            var data = res.data.data;
                            this.activity_id = parseInt(data.activity_id);
                            this.coupon = {
                                name:data.name,  //卡券名称
                                cost:data.cost,  //卡券面值等信息
                                coupon_type:data.coupon_type ? data.coupon_type : null,
                                images:data.images ? data.images : null,
                                type:data.type,  //卡券类型
                                time:data.time,  //卡券有效期
                                rule:data.rule,  //卡券使用规则
                                icon:data.icon ? data.icon : null,  //卡券的封面图片
                                expires:data.expires,  //卡券是否过期
                                number:parseInt(data.number),
                                use_number:parseInt(data.use_number)
                            };
                            this.store = {
                                id:data.store_id,
                                name:data.store_name,
                                logo:data.logo,
                                address:data.address,
                                position:data.location
                            };
                            this.$nextTick(()=>{
                                this.page_height = document.documentElement.clientHeight - this.$refs.footer.getBoundingClientRect().height;
                                if(this.store.id != 0) this.store_name_top = (this.$refs.storeLogo.getBoundingClientRect().height - this.$refs.storeName.getBoundingClientRect().height) / 2;
                            });
                            success();
                        }else{
                            error("findCoupon");
                        }
                    })
                    .catch();
            });
        },
        //卡券相关活动的兑换地址
        findActivityAfterAddress(){
            this.$http.post(this.$sysinfo.url,this.$qs.stringify({
                pages:"activity",
                doing:"easyFind",
                activity_id:this.activity_id,
                return:["entity_address"]
            }))
                .then((res)=>{
                    if(res.data.status == "success"){
                        this.after_address = res.data.data.entity_address;
                    }
                })
                .catch();
        },
        //加载门店具体位置
        storeMapPosition(){
            var mapData = {
                center:this.store.position,
                zoom:16
            };
            this.position_map.map = new this.$map.Map("store-position",mapData);
            this.position_map.map.add(
                new this.$map.Marker({
                    position:this.store.position
                })
            );
        },
        //点击底部核销使用卡券按钮
        clickAfterBtn(){
            this.after_show = true;
            //获取核销二维码
            this.getAfterQrcode()
                .then(()=>{
                    this.openTimer();
                })
                .catch(error=>{
                    this.iError(error);
                });
        },
        //获取核销二维码
        getAfterQrcode(){
            return new Promise((success,error)=>{
                this.$http.post(this.$sysinfo.url,this.$qs.stringify({
                    pages:"couponSnapshot",
                    doing:"getCouponAfterQrcode",
                    uid:this.$sysinfo.uid,
                    snapshot_id:this.snapshot_id
                }))
                    .then((res)=>{
                        if(res.data.status == "success"){
                            var data = res.data.data;
                            this.qrcode = {
                                src:data.src+"?time="+new Date().getTime(),
                                expire:data.expire
                            };
                            success();
                        }else{
                            error("getAfterQrcode");
                        }
                    })
                    .catch();
            });
        },
        //点击刷新核销二维码
        clickRefreshQrcode(){
            this.refresh_qrcode = 2;
            //获取核销二维码
            this.getAfterQrcode()
                .then(()=>{
                    this.refresh_qrcode = 0;
                    this.openTimer();
                })
                .catch(error=>{
                    this.iError(error);
                });
        },
        //开启定时器
        openTimer(){
            //开启二维码超时定时器
            clearInterval(store.state.coupon_after_expire_timer);
            store.state.coupon_after_expire_timer = setInterval(()=>{
                if(parseInt(new Date().getTime()/1000) > this.qrcode.expire){
                    this.refresh_qrcode = 1;
                    clearInterval(store.state.coupon_after_expire_timer);
                    clearInterval(store.state.coupon_timer);
                }
            },1000);
            //开启实时获取卡券信息定时器
            clearInterval(store.state.coupon_timer);
            store.state.coupon_timer = setInterval(()=>{
                this.findCouponNumber()
                    .then((data)=>{
                        this.coupon.number = data.number;
                        this.coupon.use_number = data.use_number;
                        if(parseInt(data.use_number) >= parseInt(data.number)){
                            clearInterval(store.state.coupon_after_expire_timer);
                            clearInterval(store.state.coupon_timer);
                            this.refresh_qrcode = 0;
                            this.after_show = false;
                        }
                    })
                    .catch(error=>this.iError(error));
            },300);
        },
        //获取卡券数量，兑换数量exchange和总数量number
        findCouponNumber(){
            return new Promise((success,error)=>{
                this.$http.post(this.$sysinfo.url,this.$qs.stringify({
                    pages:"couponSnapshot",
                    doing:"easyFind",
                    snapshot_id:this.snapshot_id,
                    return:["use_number","number"]
                }))
                    .then((res)=>{
                        if(res.data.status == "success"){
                            success(res.data.data);
                        }else{
                            error("findCouponNumber");
                        }
                    })
                    .catch();
            });
        },
        //点击关闭核销区域
        clickCloseAfter(){
            this.after_show = false;
            clearInterval(store.state.coupon_after_expire_timer);
            clearInterval(store.state.coupon_timer);
        },
        //显示图片预览区域
        showSlide(index){
            this.$createImagePreview({
                imgs:this.images,
                "initial-index":index
            }).show();
        },
        //错误
        iError(error){
            switch(error){
                case "findCoupon":  //获取卡券信息失败，返回首页
                    this.$router.replace("/");
                    break;
                case "getAfterQrcode":  //获取核销二维码失败
                    this.after_show = false;
                    this.$createToast({
                        time: 1000,
                        txt: "核销码获取失败，请重试",
                        type:"error"
                    }).show();
                    break;
                default:
                    //console.log(error);
                    break;
            }
        }
    }
};
</script>

<style scoped>
    #coupon{
        position:relative;
        width:355px;
        height:135px;
        margin:10px auto;
        overflow: hidden;
        padding:10px;
        box-sizing: border-box;
        color:#fff;
        font-size:14px;
    }
    #coupon.hd{
        background: url('../images/hd-bg.png') no-repeat;
        background-size: 100% 100%;
    }
    #coupon.mj{
        background: url('../images/mj-bg.png') no-repeat;
        background-size: 100% 100%;
    }
    #coupon.dh{
        background: url('../images/dh-bg.png') no-repeat;
        background-size: 100% 100%;
    }
    #coupon.dj{
        background: url('../images/dj-bg.png') no-repeat;
        background-size: 100% 100%;
    }
    #coupon.zk{
        background: url('../images/zk-bg.png') no-repeat;
        background-size: 100% 100%;
    }
    #coupon.rc{
        background: url('../images/rc-bg.png') no-repeat;
        background-size: 100% 100%;
    }
    #coupon .type{
        position:absolute;
        right:10px;
        top:10px;
        font-size:18px;
        text-shadow: 0 0 0.1em, 0 0 0.3em;
    }
    #coupon img.icon{
        float: left;
        width: 75px;
        height:75px;
        border:3px solid #fff;
        box-sizing: border-box;
        margin-right: 5px;
    }
    #coupon .name,#coupon .cost{
        float: left;
        width: 190px;
    }
    #coupon .cost{
        font-size:16px;
        margin-bottom: 10px;
    }
    #coupon .name{
        width: 250px;
    }
    #coupon .time,#coupon .number{
        position: absolute;
        bottom:13px;
        right:15px;
        font-size:14px;
        color:#fff;
    }
    #coupon .number{
        left:10px;
    }
    #coupon .status{
        position: absolute;
        top:-5px;
        right:10px;
        transform: rotate(60deg);
        opacity: .5;
        color:red;
    }
    #coupon .status.exchange{
        transform: rotate(6deg);
    }
    #coupon .status i{
        font-size:80px;
    }
    #images{
        width:100%;
        min-height:100px;
        padding:0 10px;
        box-sizing: border-box;
        overflow: hidden;
        margin-bottom: 10px;
    }
    #images h2{
        color:#000;
        font-size:16px;
        height:30px;
        line-height: 30px;
    }
    #images img{
        display: block;
        float: left;
        width: 100px;
        height:100px;
        margin: 0 27px 10px 0;
        object-fit: cover;
        border:1px solid #ccc;
        box-sizing: border-box;
    }
    #images img:nth-of-type(3n){
        margin-right:0;
    }
    #store{
        position: relative;
        width: 355px;
        margin:0 auto;
        font-size:14px;
        color:#000;
        line-height: 110%;
        padding-bottom:10px;
        border-bottom: 1px solid #eee;
    }
    #store img.logo{
        float: left;
        width:50px;
        height:50px;
        border-radius: 25px;
        margin-bottom: 5px;
    }
    #store .name{
        position: absolute;
        right:0;
        width:300px;
        float:right;
        line-height: 110%;
        vertical-align: middle;
    }
    #store .address{
        width:355px;
        clear: both;
    }
    #store #store-position{
        width:100%;
        height:150px;
        margin-top: 5px;
    }
    #after-address{
        width:355px;
        margin:0 auto;
        font-size:14px;
        color:#000;
        line-height:110%;
    }
    #rule{
        width:355px;
        margin: 0 auto 10px auto;
        font-size:14px;
        color:#000;
    }
    #rule h2{
        height:35px;
        line-height: 35px;
        font-size:16px;
    }
    #footer{
        position: fixed;
        z-index:10;
        width: 100%;
        bottom: 0;
        left:0;
    }
    .qrcode-iconfont{
        position: relative;
        top:-4px;
        width:30px;
        height:30px;
    }
    #footer span.text{
        position:relative;
        top:-14px;
        left:2px;
    }
    #after{
        position:fixed;
        z-index:20;
        top:0;
        left:0;
        bottom:0;
        right:0;
        background: rgba(0,0,0,0.7);
        text-align: center;
        color:#fff;
        font-size:14px;
    }
    #after .after{
        position:absolute;
        top:50%;
        transform: translateY(-50%);
        width: 100%;
    }
    #after .after h2{
        margin-bottom: 5px;
    }
    #after .after img.qrcode{
        display: block;
        margin: 0 auto;
        width:200px;
        height:200px;
    }
    #after .after .past{
        position: absolute;
        bottom:0;
        left:50%;
        transform: translateX(-50%);
        width:200px;
        height:200px;
        background: rgba(0,0,0,.6);
        text-align: center;
    }
    #after .after .past .past-content{
        position: absolute;
        top:50%;
        transform: translateY(-50%);
        width: 100%;
    }
    #after .after .past .past-content img{
        width:100px;
        display: block;
        margin: 0 auto;
    }
    #after .close{
        position: absolute;
        right:15px;
        top:10px;
    }
    #after .close i{
        font-size:30px;
    }
</style>
